package cn.smbms.controller;

import cn.smbms.beans.Role;
import cn.smbms.beans.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Consts;
import cn.smbms.tools.PageSupport;
import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ Author   ：陈慧杰
 * @ Date     ：Created in 15:20 2021/12/4
 */
@Controller
@RequestMapping("user")
       public class UserController {
          private Logger log =  Logger.getLogger(UserController.class);
        @Autowired
         @Qualifier("userService")
          private UserService userService;
        @Autowired
        @Qualifier("roleService")
        private RoleService roleService;
@RequestMapping("index.html")
         public String index(){
            log.debug("控制台");
            return "index";
   }
   @RequestMapping("dologin.html")
    public String dologin(@RequestParam("userCode") String userName, @RequestParam("userPassword") String password, HttpSession httpSession , HttpServletRequest request){
    log.debug("控制器开始执行登录");
       User user = userService.login(userName, password);
       if (null != user){
           log.debug("数据库存在用户");
           httpSession.setAttribute("user",user);
            return "redirect:/user/frame.html";
    }else {
           log.debug("查询不到");
           request.setAttribute("message" , "用户名或者没密码不正确");
           return "index";
       }
   }
   @RequestMapping("frame.html")
   public  String frame(){
    return "frame";
   }
@RequestMapping("userList.html")
   public ModelAndView userList(User user, HttpServletRequest request , HttpServletResponse response) throws IOException {
    String queryname = request.getParameter("queryname");
    String queryUserRole = request.getParameter("queryUserRole");
    String pageIndex = request.getParameter("pageIndex");
    int pageSize = Consts.pageSize;
    Integer  userRole=0 ;
    int currentPageNo =1;

    if(queryname == null){
        queryname = "";
    }
    if(queryUserRole != null && !queryUserRole.equals("")){
        userRole = Integer.parseInt(queryUserRole);
    }
    if(pageIndex != null){
        try{
            currentPageNo = Integer.valueOf(pageIndex);
        }catch(NumberFormatException e){
            response.sendRedirect("error.jsp");
        }
    }

    // 计算页码
    int totalCount	= userService.getUserCount(queryname,queryUserRole);
    System.out.println("总数量" + totalCount );
    //总页数
    PageSupport pages=new PageSupport();
    pages.setCurrentPageNo(currentPageNo);
    pages.setPageSize(pageSize);
    pages.setTotalCount(totalCount);
    pages.setTotalPageCountByRs();
    int totalPageCount = pages.getTotalPageCount();

    //控制首页和尾页
    if(currentPageNo < 1){
        currentPageNo = 1;
    }else if(currentPageNo > totalPageCount){
        currentPageNo = totalPageCount;
    }

    List<User> userList = userService.getUserList(user,queryname,queryUserRole,currentPageNo,pageSize);
    List<Role> roleList = roleService.getRoleList();
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("userList",userList);
    modelAndView.addObject("roleList",roleList);
    modelAndView.addObject("totalCount", totalCount);
    modelAndView.addObject("totalPageCount" , totalPageCount );
    modelAndView.addObject("currentPageNo", currentPageNo);
    modelAndView.setViewName("userList");
    return modelAndView;
}

//添加用户
@RequestMapping("addUser.html")
    public  String addUser(){
    return "useradd";
}
    // 执行用户添加
    @RequestMapping("doAddUser.html")
    public String doAddUser(String userCode , String userName , String userPassword , String gender , String birthday ,String phone , String address , String userRole ) throws ParseException {
        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setGender(Integer.parseInt(gender));
        user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.parseInt(userRole));
        user.setCreationDate(new Date());
        int affectRows = userService.addUser(user);
        if ( affectRows > 0 ) {
            return "redirect:/user/userList.html";
        }else {
            return "redirect:/user/addUser.html" ;
        }
    }
// 判断用户码是否被占用
    @RequestMapping("ucExist.html")
    @ResponseBody
    public String ucExist(String userCode){
        HashMap<String,String> map = new HashMap<String , String>();
        User user = userService.ucExist(userCode);
        if (user != null){
            map.put("userCode" , "exist");
        }else {
            map.put("userCode", "noExist");
        }
        System.out.println("校验" + map.get("userCode"));
        return JSONArray.toJSONString(map);
    }

    // 删除用户
    @RequestMapping("deleteUser.html")
    @ResponseBody
    public String deleteUser(String uid) {
        HashMap<String, String> map = new HashMap<>();
        int affectRows = userService.deleteUser(uid);
        Integer id = Integer.parseInt(uid);
        if (id < 0) {
            map.put("delResult" ,"notexist");
        }else {
            if (affectRows > 0 ) {
                map.put("delResult" , "true");
            }else {
                map.put("delResult" , "false");
            }
        }
        return  JSONArray.toJSONString(map);
    }
    //查看用户
    @RequestMapping("userView.html")
    public ModelAndView userView(String uid){
      User user = userService.userView(uid);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user",user);
        modelAndView.setViewName("userview");
       return  modelAndView;
    }
    //修改用户
    @RequestMapping("modifyUser.html")
    public ModelAndView modifyUser(String uid){
        User user = userService.userView(uid);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user",user);
        modelAndView.setViewName("usermodify");
        return  modelAndView;
    }
//执行用户修改操作
    @RequestMapping("doUserModify.html")
    public String doUserModify( String uid,String userName, String gender, String phone,String address,String userRole) throws ParseException {
        User user = new User();
        user.setId(Integer.parseInt(uid));
        user.setUserName(userName);
        user.setGender(Integer.parseInt(gender));
      //  user.setBirthday(new SimpleDateFormat("yyyy--MM--dd").parse(birthday));
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.parseInt(userRole));
         int affectRows=  userService.doUserModify(user);
        if ( affectRows >0 ) {
            return "redirect:/user/userList.html";
        }else {
            return "redirect:/user/modifyUser.html";
        }
    }
    //跳转修改密码页面
 @RequestMapping("pwdUpadte.html")
    public  String pwdUpadte(){
        return   "pwdmodify";
    }
//    //查看密码修改
//@RequestMapping("lookPwd.html")
//    private void getPwdByUserId(HttpSession httpSession,HttpServletRequest request, HttpServletResponse response)
//            throws ServletException, IOException {
//        String oldpassword = request.getParameter("oldpassword");
//        Map<String, String> resultMap = new HashMap<String, String>();
//        User user = new User();
//    httpSession.setAttribute("user",user);
//       if(StringUtils.isNullOrEmpty(oldpassword)){//旧密码输入为空
//            resultMap.put("result", "error");
//        }else{
//            String sessionPwd = ((User)user).getUserPassword();
//            if(oldpassword.equals(sessionPwd)){
//                resultMap.put("result", "true");
//            }else{//旧密码输入不正确
//                resultMap.put("result", "false");
//            }
//        }
//        response.setContentType("application/json");
//        PrintWriter outPrintWriter = response.getWriter();
//        outPrintWriter.write(JSONArray.toJSONString(resultMap));
//        outPrintWriter.flush();
//        outPrintWriter.close();
//    }
@RequestMapping(value = "yanPwd.html")
@ResponseBody
    public  String yanPwd( HttpSession httpSession , String oldpassword){
    log.debug("密码："+oldpassword);
    User user = (User) httpSession.getAttribute("user");
    String pwd = userService.yanPwd(user.getId());
    log.debug("查到数据库密码1：" + pwd );
    HashMap<String, String> map = new HashMap<>();
    if (null == user){
         map.put("result","sessionerror");
    }
    if (! pwd.trim().equals(oldpassword.trim())  ){
        map.put("result","false");
    }
    if ( oldpassword  == null || oldpassword == "" ){
   map.put("result","error");
    }
    if ( pwd.trim().equals(oldpassword.trim())) {
        map.put("result" , "true");
    }
    return   JSONArray.toJSONString(map);

}

        //执行密码修改
@RequestMapping("doPwd.html")
    private String getPwdByUserId(String newpassword ,HttpSession httpSession){
    User user = (User) httpSession.getAttribute("user");
    Integer id = user.getId();
    int affect = userService.getPwdByUserId(newpassword, id);
    if (affect>0){
        return "redirect:/user/index.html";
    }else {
        return "redirect:/user/pwdUpadte.html";
    }


}
}